//
//  BSTopicTableViewController.m
//  baisibudejie
//
//  Created by 陈博文 on 16/2/2.
//  Copyright © 2016年 陈博文. All rights reserved.
//

#import "BSTopicTableViewController.h"

#import "BSTopic.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import <MJExtension.h>
#import <MJRefresh/MJRefresh.h>

#import "BSHeader.h"
#import "BSFooter.h"
#import "BSHTTPSessionManager.h"

#import "BSTopicCell.h"
#import "BSTopicVideoView.h"

#import "BSAllViewController.h"
#import "BSPictureViewController.h"
#import "BSVideoViewController.h"
#import "BSWordViewController.h"

#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>

@interface BSTopicTableViewController ()
/** mgr*/
@property (nonatomic ,weak) BSHTTPSessionManager *mgr;
/** topics*/
@property (nonatomic ,strong) NSMutableArray *topics;
/** 用来加载下一页数据 */
@property (nonatomic, copy) NSString *maxtime;

/** =======上拉刷新控件===== */
/** 上拉刷新控件 */
@property (nonatomic, weak) UIView *footer;
/** 上拉刷新控件label */
@property (nonatomic, weak) UILabel *footerLabel;
/** 上拉刷新状态 */
@property(nonatomic, assign, getter=isLoadingMoreData) BOOL loadingMoreData;
/** =======上拉刷新控件===== */



/** =======下拉刷新控件===== */

@property (nonatomic, weak) UIView *header;
/** 下拉刷新控件 */
@property (nonatomic, weak) UILabel *headerLabel;
/** 是否为"松开立即刷新" */
@property(nonatomic, assign, getter=isWillLoadingNewData) BOOL willLoadingNewData;
/** 是否为"正在刷新" */
@property(nonatomic, assign, getter=isLoadingNewData) BOOL loadingNewData;
/** =======下拉刷新控件===== */

/** =======视频播放控件===== */
/** player*/
@property (nonatomic ,strong) AVPlayer *avPlayer;
/** avlayer*/
@property (nonatomic ,strong) AVPlayerLayer *avPlayLayer;
/** playView*/
@property (nonatomic ,weak) UIView *playView;
/** index*/
@property (nonatomic ,assign) NSInteger index;
/** =======视频播放控件===== */
@end

@implementation BSTopicTableViewController

static NSString * const BSTopicCellId = @"topic";
/**
 *使用懒加载
 */
- (BSHTTPSessionManager *)mgr
{
    if (!_mgr) {
        _mgr = [BSHTTPSessionManager manager];
    }
    return _mgr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpTableView];
    // 集成刷新控件
    [self setUpRefresh];
   
}


-(void)setUpTableView{
    
    self.tableView.contentInset = UIEdgeInsetsMake(BSNavMaxY + BSTitlesViewH, 0, BSTabBarH, 0);
    //设置指示条的偏移量
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    // 注册cell
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BSTopicCell class]) bundle:nil] forCellReuseIdentifier:BSTopicCellId];
    
    // 设置cell的高度
//    self.tableView.rowHeight = 200;
}
/**
 *  刷新动作
 */

- (void)setUpRefresh
{
    // 下拉刷新:加载最新的数据
    self.tableView.mj_header = [BSHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopics)];
    
    //确保一一开始就刷新
    [ self.tableView.mj_header beginRefreshing];
    // 上拉刷新:加载更多的数据
    
    self.tableView.mj_footer = [BSFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopics)];
}

-(BSTopicType)type{
    return 0;
}

#pragma mark ---------------
#pragma mark - 获取数据
/**
 *获取新数据
 */
- (void)loadNewTopics
{
    // 拼接请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"data";
    parameters[@"type"] = @(self.type); // @1
    
    // 发送请求
    [self.mgr GET:baseUrl parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        getPlist(data);
        self.maxtime = responseObject[@"info"][@"maxtime"];
        // 字典数组 -> 模型数组
        self.topics = [BSTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        // 刷新表格
        [self.tableView reloadData];
        // 结束刷新
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        BSLog(@"请求失败 - %@", error);
        // 结束刷新
        
        [self.tableView.mj_header endRefreshing];
    }];
}

/**
 *  加载更多数据
 */
- (void)loadMoreTopics
{
    //每次运行刷新的时候,柱塞2s
    BSFunc
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"a"] = @"list";
        parameters[@"c"] = @"data";
        parameters[@"type"] = @(self.type); // @1
        parameters[@"maxtime"] = self.maxtime;
        // 发送请求
        [self.mgr GET:baseUrl parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            self.maxtime = responseObject[@"info"][@"maxtime"];
            // 字典数组 -> 模型数组
            // 字典数组 -> 模型数组
            NSArray *moreTopics = [BSTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
            [self.topics addObjectsFromArray:moreTopics];
            // 刷新表格
            [self.tableView reloadData];
            // 有数据了
            [self.tableView.mj_footer endRefreshing];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            BSLog(@"请求失败 - %@", error);
            // 结束刷新
            [self.tableView.mj_footer endRefreshing];
            
        }];
        
    });
    
}


#pragma mark - 数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.topics.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BSTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:BSTopicCellId];
    cell.topic = self.topics[indexPath.row];
    
    
    if (cell.topic.type == BSTopicTypeVideo) {
        cell.videoView.playButton.tag = indexPath.row;
        [cell.videoView.playButton addTarget:self action:@selector(setUpVideo:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return cell;
}

#pragma mark ---------------
#pragma mark - 计算高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //定义一个属性,用来赋值
    BSTopic *topic = self.topics[indexPath.row];
    return topic.cellHeight;
}

#pragma mark ---------------
#pragma mark - 设置播放控件
-(void)setUpVideo:(UIButton *)button{
    
    [self.playView removeFromSuperview];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
   
    BSTopicCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    self.index = indexPath.row;
    
    UIView *avView = [[UIView alloc]init];
    avView.frame = cell.videoView.frame;
    avView.backgroundColor = [UIColor redColor];
    self.playView = avView;
    [cell addSubview:self.playView];
    
    //定义一个属性,用来赋值
    BSTopic *topic = self.topics[indexPath.row];
    NSURL *remoteURL = [NSURL URLWithString:topic.videouri];
    self.avPlayer = [AVPlayer playerWithURL:remoteURL];
    [self.avPlayer play];
    
    //显示播放的视屏
    self.avPlayLayer = [AVPlayerLayer  playerLayerWithPlayer:self.avPlayer];
    self.avPlayLayer.frame = avView.bounds;
    [self.playView.layer addSublayer:self.avPlayLayer];
}


#pragma mark ---------------
#pragma mark - 计算是否在屏幕中

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == self.index) {
        
        [self.avPlayer pause];
        [self.playView removeFromSuperview];
        
    }
}

#pragma mark ---------------
#pragma mark - 屏幕切换的时候移除视屏播放
-(void)setUpPlayView{
    
    [self.avPlayer pause];
    [self.playView removeFromSuperview];

}
@end
